[入門]API Gatewayを利用してS3バケットのオブジェクトを一覧表示させてみた

[入門]API Gatewayを利用してS3バケットのオブジェクトを一覧表示させてみた

Clock Icon2024.09.29

こんにちは。中村です。

はじめに

API Gatewayってサービスはよく耳にするけれど、実は利用したことがないという方は意外と多いのではないでしょうか?
今回は、入門として、特定のS3バケットにあるオブジェクトを一覧表示するAPIを作成してみます。
マネジメントコンソールからの作成手順は、下記公式ドキュメントのチュートリアルを参考にしてください。

https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/integrating-api-with-aws-services-s3.html

今回は、CloudFormationテンプレートを用いて作成してみます。
AWS公式ドキュメントのチュートリアル「呼び出し元の Amazon S3 バケットを一覧表示する API のメソッドを公開する」を参考にしたテンプレートです。

やってみる

テンプレートを作成してみる

AWSTemplateFormatVersion: "2010-09-09"

Parameters:
  AppName: 
    Description: Application Name.
    Type: String
    Default: api-gateway-s3-list

Resources:
# ==========
# S3
# ==========
  S3Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketEncryption: 
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      BucketName: !Sub "api-gateway-s3-${AWS::AccountId}"
      OwnershipControls: 
        Rules:
          - ObjectOwnership: BucketOwnerEnforced
      PublicAccessBlockConfiguration: 
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
# ==========
# API Gateway
# ==========
  ApiGatewayRestApi:
    Type: AWS::ApiGateway::RestApi
    Properties:
      BinaryMediaTypes: 
        - 'image/*'
      EndpointConfiguration: 
        Types:
          - REGIONAL
      Name: !Ref AppName
  ApiGatewayMethodRootList:
    Type: AWS::ApiGateway::Method
    Properties:
      AuthorizationType: AWS_IAM
      HttpMethod: GET
      Integration:
        Type: AWS
        IntegrationHttpMethod: GET
        Uri: !Sub "arn:aws:apigateway:${AWS::Region}:s3:path/${S3Bucket}/"
        IntegrationResponses:
          - StatusCode: 200
            ResponseParameters:
              method.response.header.Content-Length : integration.response.header.Content-Length
              method.response.header.Content-Type : integration.response.header.Content-Type
              method.response.header.Timestamp : integration.response.header.Date
          - StatusCode: 400
            SelectionPattern: '4\d{2}'
            ResponseTemplates:
              application/json: '{"error": "Client error"}'
          - StatusCode: 500
            SelectionPattern: '5\d{2}'
            ResponseTemplates:
              application/json: '{"error": "Server error"}'
        Credentials: !GetAtt ApiGatewayS3RoleRootList.Arn
      MethodResponses:
        - StatusCode: 200
          ResponseParameters:
            method.response.header.Content-Type: true
            method.response.header.Content-Length: true
            method.response.header.Timestamp: true
        - StatusCode: 400
        - StatusCode: 500
      ResourceId: !GetAtt ApiGatewayRestApi.RootResourceId
      RestApiId: !Ref ApiGatewayRestApi
  ApiGatewayS3RoleRootList:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal:
              Service: apigateway.amazonaws.com
            Action: 'sts:AssumeRole'
      Policies:
        - PolicyName: APIGatewayS3ProxyPolicy-ListPolicy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - s3:ListBucket
                Resource: 
                  - !Sub "arn:aws:s3:::${S3Bucket}"
      Path: /
      RoleName: APIGatewayS3ProxyPolicy-List

やってみた

  1. 上記テンプレートを利用してCloudFormationでリソースを作成する
  2. 作成されたS3バケットに任意のファイルをアップロードする
  3. API Gatewayサービスから、作成したAPIの「テスト」タブを表示させる

api-gateway-s3-list-img-2

  1. 「テスト」を押下する

api-gateway-s3-list-img-3

  1. レスポンスを確認する

api-gateway-s3-list-img-4

  1. xml形式で2でアップロードしたファイル名が出力されていることが確認できます。

さいごに

今回はチュートリアルを参考に、バケット内のファイルを一覧表示してみました。
AWS統合を利用したレスポンスだと、xml形式で一覧が取得できることがわかります。
json形式でレスポンスが欲しい場合は、Lambda統合に構成を変更してもいいかもしれません。

参考

https://dev.classmethod.jp/articles/api-gateway-proxy-to-s3-list-objects-by-cdk/

https://docs.aws.amazon.com/ja_jp/apigateway/latest/developerguide/integrating-api-with-aws-services-s3.html

この記事をシェアする

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.